package com.financing.wap.common;

import java.awt.AlphaComposite;
import java.awt.Color;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.geom.AffineTransform;
import java.awt.geom.Ellipse2D;
import java.awt.image.BufferedImage;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import javax.imageio.ImageIO;
import javax.imageio.stream.ImageOutputStream;

import org.apache.axis.utils.StringUtils;

import com.financing.wap.util.AliyunOssUtil;
import com.financing.wap.util.PropertiesUtils;

public class ImgUtil {
	private static String fileBaseDir = PropertiesUtils.getValue("fileBaseDir");

	/**
	 * 理财师工具 - 二维码海报绘图
	 * 
	 * @param backUrl
	 * @param headUrl
	 * @param text1
	 * @param erweimaUrl
	 * @param text2
	 * @return
	 */
	public static String makeImg(String backUrl,String headUrl,String text1,String erweimaUrl,String text2, String userFlag, String isuseoss)  {

		//		 backUrl = "http://wp5.superfa.cn//upload/faUser/cert/20170821/150329767386320170821144328.jpg?x-oss-process=image/resize,w_750";
		//		 headUrl = "http://wp5.superfa.cn/upload/faUser/cert/20170822/150338631664420170822152107.jpg?x-oss-process=image/resize,m_fixed,h_140,w_140";
		//		 text1 = "店铺简介，我的小店我的理财师店铺我的小店我的理财师店铺我的sdfsdfsjhdfjhsdkfjkdsjfkj店我的理财师店铺我的小店我的理财师店铺我的小店我的理财师店铺";
		//		 erweimaUrl = "http://wp5.superfa.cn/upload/faUser/shop/132qrcode.png?x-oss-process=image/resize,m_fixed,h_140,w_140";
		//		 text2 = "张哥";
		try {
			BufferedImage baseImg = getBufferedImage(backUrl);
			BufferedImage headImg = getBufferedImage(headUrl);
			BufferedImage erweima = getBufferedImage(erweimaUrl);

			BufferedImage buffImg0 = ImgUtil.markback(baseImg, 1.0f);
			BufferedImage buffImg1 = ImgUtil.markhead(buffImg0,
					headImg, 1.0f);
			BufferedImage buffImg2 = ImgUtil.marktext(buffImg1,
					text1, text2, 1.0f);
			BufferedImage buffImg3 = ImgUtil.markerweima(buffImg2,
					erweima, 1.0f);
			// 输出水印图片
			ByteArrayOutputStream bs =new ByteArrayOutputStream();
			ImageOutputStream imOut =ImageIO.createImageOutputStream(bs);
			ImageIO.write(buffImg3,"png",imOut);
			InputStream is =new ByteArrayInputStream(bs.toByteArray());

			StringBuffer fileFullPath = new StringBuffer();
			fileFullPath.append(fileBaseDir)
			.append("/upload")
			.append("/faUser")
			.append("/shop")
			.append("/")
			.append(userFlag+".png");
			
/*			ImageIO.write(buffImg3, "PNG", new File("/Users/zhangsu/Documents/abc.png"));
			
			return null;*/

			if(org.apache.commons.lang.StringUtils.equals(isuseoss, "0")) {
				String filePath = org.apache.commons.lang.StringUtils.replace(fileFullPath.toString(),fileBaseDir+"/","");
				AliyunOssUtil.writeFile(is, filePath);
				return "/"+filePath;
			} else {
				ImageIO.write(buffImg3, "PNG", new File(fileFullPath.toString()));
				return fileFullPath.toString().replace(fileBaseDir, "");
			}
			
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 绘制二维码图层
	 * 
	 * @param buffImg
	 * @param erweima
	 * @param alpha
	 * @return
	 * @throws IOException
	 */
	public static BufferedImage markerweima(BufferedImage buffImg, BufferedImage erweima, float alpha) throws IOException {
		// 创建Graphics2D对象，用在底图对象上绘图
		Graphics2D g2d = buffImg.createGraphics();
		// 在图形和图像中实现混合和透明效果
		g2d.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP,
				alpha));	

		g2d.drawImage(erweima, 220, 580, 230, 230, null);
		g2d.dispose();// 释放图形上下文使用的系统资源
		return buffImg;
	}

	/**
	 * 绘制文字
	 * 
	 * @param buffImg
	 * @param text1
	 * @param text2
	 * @param alpha
	 * @return
	 * @throws IOException
	 */
	public static BufferedImage marktext(BufferedImage buffImg,String text1 , String text2, float alpha)
			throws IOException {

		// 获取层图
		// 创建Graphics2D对象，用在底图对象上绘图
		Graphics2D g2d = buffImg.createGraphics();
		// 在图形和图像中实现混合和透明效果
		g2d.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP,
				alpha));
		// 绘制
		Font font = new Font("微软雅黑", Font.PLAIN, 28);
		g2d.setFont(font);
		g2d.setColor(Color.BLACK);

		FontMetrics m = g2d.getFontMetrics();
		if(!StringUtils.isEmpty(text1)) {
			int y = 460; 
			if(m.stringWidth(text1) < 600) {
				g2d.drawString(text1, 20, y);
			} else {
				String[] words = text1.split("");
				String currentLine = words[0];

				int curlinenum = 0;
				for(int i = 1; i < words.length; i++) {
					if(m.stringWidth(currentLine+words[i]) < 600) {
						if(curlinenum==1) {
							if(m.stringWidth(currentLine+words[i]) < 300) {
								currentLine += ""+words[i];
							} else {
								currentLine += "...";
								break;
							}
						} else {
							currentLine += ""+words[i];
						}
					} else {
						g2d.drawString(currentLine, 20, y);
						y += m.getHeight();
						currentLine = words[i];

						curlinenum ++;
					}
				}
				if(currentLine.trim().length() > 0) {
					g2d.drawString(currentLine, 20, y);
				}
			}
		}
		
		if(!StringUtils.isEmpty(text2)) {
			int x = (600 - m.stringWidth(text2))/2+30;
	
			g2d.drawString(text2, x, 405);
		}
		g2d.drawString("扫描二维码进店铺", 220, 860);

		g2d.dispose();// 释放图形上下文使用的系统资源
		return buffImg;
	}

	/**
	 * 绘制背景
	 * 
	 * @param baseImg
	 * @param alpha
	 * @return
	 * @throws IOException
	 */
	public static BufferedImage markback(BufferedImage baseImg, float alpha) throws IOException {
		BufferedImage buffImg = new BufferedImage(640, 950, BufferedImage.TYPE_INT_RGB);
		// 创建Graphics2D对象，用在底图对象上绘图
		Graphics2D g2d = buffImg.createGraphics();
		g2d.fillRect(0, 0, 640, 950);
		g2d.setColor(Color.WHITE);
		// 在图形和图像中实现混合和透明效果
		g2d.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP,
				alpha));	

		g2d.drawImage(baseImg, 0, 0, 640, 640, null);
		
		g2d.fillRect(0, 320, 640, 320);
		g2d.dispose();// 释放图形上下文使用的系统资源
		return buffImg;
	}

	/**
	 * 绘制头像
	 * 
	 * @param baseImg
	 * @param waterImg
	 * @param alpha
	 * @return
	 * @throws IOException
	 */
	public static BufferedImage markhead(BufferedImage baseImg, BufferedImage waterImg, float alpha) throws IOException {
		BufferedImage tempBuffer = new BufferedImage(150, 150, BufferedImage.TYPE_INT_BGR);
		Graphics headG2d = tempBuffer.getGraphics();
		headG2d.drawImage(waterImg, 0, 0, 150, 150,null);
		headG2d.dispose();

		// 创建Graphics2D对象，用在底图对象上绘图
		Graphics2D g2d = baseImg.createGraphics();
		// 在图形和图像中实现混合和透明效果
		g2d.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP,
				alpha));	

		Ellipse2D.Double shape = new Ellipse2D.Double(260, 220, tempBuffer.getHeight(), tempBuffer.getWidth());
		g2d.setClip(shape);

		AffineTransform at = null;
		at = at.getTranslateInstance(260, 220);
		g2d.setTransform(at);

		g2d.drawImage(tempBuffer, 0, 0, null);
		g2d.dispose();// 释放图形上下文使用的系统资源
		return baseImg;
	}

	private static BufferedImage getBufferedImage(String v){

		try {
			URL url = new URL(
					v);
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			// 设置超时间为3秒
			conn.setConnectTimeout(3 * 1000);
			// 防止屏蔽程序抓取而返回403错误
			conn.setRequestProperty("User-Agent",
					"Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
			// 得到输入流
			InputStream input = conn.getInputStream();
			return ImageIO.read(input);
		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}
	//链接url下载图片
	public static void downloadPicture(String urlList ,String imageName) {
		URL url = null;
		int imageNumber = 0;

		try {
			url = new URL(urlList);
			DataInputStream dataInputStream = new DataInputStream(url.openStream());


			FileOutputStream fileOutputStream = new FileOutputStream(new File(imageName));
			ByteArrayOutputStream output = new ByteArrayOutputStream();

			byte[] buffer = new byte[1024];
			int length;

			while ((length = dataInputStream.read(buffer)) > 0) {
				output.write(buffer, 0, length);
			}
			byte[] context=output.toByteArray();
			fileOutputStream.write(output.toByteArray());
			dataInputStream.close();
			fileOutputStream.close();
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	public static void main(String[] args) throws Exception {

/*		String backUrl = "https://static-superfa-cn.alikunlun.com/upload/faUser/cert/20171003/1507038935625ios469028.png?x-oss-process=image/resize,w_600";
		String headUrl = "https://static-superfa-cn.alikunlun.com/upload/faUser/cert/20171003/1506999821885ios385066.png";
		String text1 = "店铺简介，我的小店我的理财师店铺我的小店我的理财师店铺我的sdfsdfsjhdfjhsdkfjkdsjfkj店我的理财师店铺我的小店我的理财师店铺我的小店我的理财师店铺";
//		String erweimaUrl = "http://wp5.superfa.cn/upload/faUser/shop/132qrcode.png?x-oss-process=image/resize,m_fixed,h_140,w_140";
		String erweimaUrl = "https://static-superfa-cn.alikunlun.com/upload/faUser/shop/6qrcode.png";
		String text2 = "张小哥";
		System.out.println(makeImg(backUrl, headUrl, text1, erweimaUrl, text2, "abc", "1"));*/
			String a = "http://wx.qlogo.cn/mmopen/vi_32/Q0j4TwGTfTJYkXv4v8zjmVm6UVOkdu6xjhgTrqic4j3eicqVTL6zQuiadkRS6P2tXGtnaPRB4hXtpKUfiaicF5hGquA/64";
		a= a.replace("/64","/0");
		downloadPicture(a,"d://2.jpg");

	}
}
